package com.hg.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import com.hg.pojo.HgMallShop;
import com.hg.pojo.HgUser;
import com.hg.service.HgMallShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@CrossOrigin
public class HgMallShopController {


    @Autowired
    private HgMallShopService hgMallShopService;

    /**
     * 获取所有店铺信息
     *
     * @param currentPage 页面
     * @param pageSize    页面大小
     * @return {@link R}<{@link Page}<{@link HgMallShop}>>
     */
    @GetMapping("/shopList")
    public R<Page<HgMallShop>> getList(int currentPage, int pageSize, String person, String shopname, String category, String place, String phones) {
        Page<HgMallShop> pageInfo = new Page<>(currentPage, pageSize);
        LambdaQueryWrapper<HgMallShop> lm = new LambdaQueryWrapper<>();
        lm.eq(HgMallShop::getDelFlag, 0);
        lm.orderByDesc(HgMallShop::getCreateTime);
        lm.like(category != "", HgMallShop::getCategory, category);
        lm.like(shopname != "", HgMallShop::getName, shopname);
        lm.like(place != "", HgMallShop::getPlace, place);
        lm.like(phones != "", HgMallShop::getPhone, phones);
        lm.like(person != "", HgMallShop::getPerson, person);
        lm.select(
                HgMallShop::getId,
                HgMallShop::getName,
                HgMallShop::getIntrodce,
                HgMallShop::getCategory,
                HgMallShop::getPlace,
                HgMallShop::getPerson,
                HgMallShop::getPhone,
                HgMallShop::getStatus,
                HgMallShop::getDelFlag,
                HgMallShop::getIcon);
        hgMallShopService.page(pageInfo, lm);
        return R.success(HttpStatus.SHOP_SUCCESS, pageInfo);
    }

    /*
     * 添加店铺
     * */
    @PostMapping("/addShop")
    public R saveShop(@RequestBody HgMallShop hgMallShop) {
        hgMallShopService.save(hgMallShop);
        return R.success(HttpStatus.SHOP_SUCCESS,"添加成功");
    }

    /**
     * 伪删除店鋪信息
     *
     * @param id id
     * @return {@link R}
     */
    @DeleteMapping("/shopDelete/{id}")
    @Transactional
    public R deleteShop(@PathVariable Integer id) {

        int i = hgMallShopService.deleteShopById(id);
        if (i == 0) {
            return R.error(HttpStatus.SHOP_ERROR, "删除错误");
        } else {
            return R.success(HttpStatus.SHOP_SUCCESS,"删除成功");
        }

    }


    /**
     * 更新店铺信息
     *
     * @param hgMallShop hg购物中心店
     * @return {@link R}
     */
    @PutMapping("/updateShop")
    public R updateShop(@RequestBody HgMallShop hgMallShop) {
        hgMallShopService.updateShop(hgMallShop);
        return R.success(HttpStatus.SHOP_SUCCESS,"更新成功");
    }


    /**
     * 伪删除商店ids
     *
     * @param ids ids
     * @return {@link R}
     */
    @PostMapping("/deleteShopIds/{ids}")
    public R deleteShopIds(@PathVariable Integer[] ids) {
        hgMallShopService.deleteShopByIds(ids);
        return R.success(HttpStatus.SHOP_SUCCESS,"删除成功");
    }

    /**
     * 更新状态
     *
     * @param id     id
     * @param status 状态
     * @return {@link R}
     */
    @PutMapping("/updateStatus/{id}/{status}")
    public R updateStatus(@PathVariable Long id,@PathVariable int status) {

        if (id!=null){
            LambdaUpdateWrapper<HgMallShop> lm = new LambdaUpdateWrapper<>();
            lm.set(HgMallShop::getStatus, status);
            lm.eq(HgMallShop::getId, id);
            hgMallShopService.update(lm);
            return R.success(HttpStatus.SHOP_SUCCESS,"更新成功");
        }
       return R.error(HttpStatus.SHOP_ERROR,"传入的id为空");
    }

    /**
     * 获取选择选项
     *
     * @return {@link R}<{@link List}<{@link HgMallShop}>>
     */
    @GetMapping("/selectOptions")
    public R<List<HgMallShop>> selectOptions(){
        LambdaQueryWrapper<HgMallShop> lm =new LambdaQueryWrapper<>();
        lm.select(HgMallShop::getId,HgMallShop::getName);
        lm.eq(HgMallShop::getDelFlag,0);
        List<HgMallShop> list = hgMallShopService.list(lm);
        if (list!=null){
            return R.success(HttpStatus.SHOP_SUCCESS,list);
        }
        return R.error(HttpStatus.SHOP_ERROR,"查询错误");
    }


    @GetMapping("/mySelectShopId/{shopId}")
    public R<List<HgMallShop>> selectShopOne(@PathVariable Long shopId){
        LambdaQueryWrapper<HgMallShop> lm =new LambdaQueryWrapper<>();
        lm.select(
                HgMallShop::getId,
                HgMallShop::getName,
                HgMallShop::getIntrodce,
                HgMallShop::getCategory,
                HgMallShop::getPlace,
                HgMallShop::getPerson,
                HgMallShop::getPhone,
                HgMallShop::getStatus,
                HgMallShop::getDelFlag,
                HgMallShop::getIcon);
        lm.eq(HgMallShop::getId,shopId);
        lm.eq(HgMallShop::getDelFlag,0);
        List<HgMallShop> list = hgMallShopService.list(lm);
        if (list!=null){
            return R.success(HttpStatus.SHOP_SUCCESS,list);
        }
        return R.error(HttpStatus.SHOP_ERROR,"未创建店铺");
    }


    /**
     *
     */
    @PostMapping("/MyShopAdd/{id}")
    public R MyShopAdd(@PathVariable Integer id,@RequestBody HgMallShop hgMallShop){

      int addOne=  hgMallShopService.MyShopAddOne(id,hgMallShop);
      if (addOne>0){
          return R.success(HttpStatus.SHOP_SUCCESS,"添加成功");

      }
      return R.error(HttpStatus.SHOP_ERROR,"添加失败");
    }

    /**
     * 导出接口
     */
    @GetMapping("/shopExport")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        LambdaQueryWrapper<HgMallShop> lm = new LambdaQueryWrapper<>();
        lm.select(
                HgMallShop::getId,
                HgMallShop::getName,
                HgMallShop::getIntrodce,
                HgMallShop::getCategory,
                HgMallShop::getPlace,
                HgMallShop::getPerson,
                HgMallShop::getPhone,
                HgMallShop::getStatus,
                HgMallShop::getDelFlag,
                HgMallShop::getIcon);
        List<HgMallShop> list = hgMallShopService.list(lm);
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id", "店铺ID");
        writer.addHeaderAlias("name", "店铺名称");
        writer.addHeaderAlias("introdce", "店铺介绍");
        writer.addHeaderAlias("category", "店铺类别");
        writer.addHeaderAlias("phone", "店铺地点");
        writer.addHeaderAlias("status", "店铺状态");
        writer.addHeaderAlias("person", "联系人");
        writer.addHeaderAlias("phone", "联系电话");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("店铺信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
}
